//应用根目录
var app_root_path = "";
//数据格式
var MediType_FORM_URLENCODE = "application/x-www-form-urlencoded; charset=UTF-8";
var MediType_JSON = "application/json; charset=UTF-8";
//处理权限按键
$(function () {
    permissonHandler();
})
if (!Api) {
    //接口定义处
    var Api = {
        debug: true,
        //接口demo，若api没指定，method:默认为get方法提交
        ajaxDemo: {
            formAdd: {
                //form 表单提交例子
                url: app_root_path + "/api/ajax/formAdd",
                method: "POST",
                contentType: MediType_FORM_URLENCODE,
                //需要提交的参数模型
                paramModel: {
                    id: undefined,//
                    text: undefined,
                    name: undefined,
                    age: undefined,
                    school: undefined,
                    teacher: {
                        name: undefined,
                        address: undefined,
                        level: undefined,
                    }
                }

            },
            // json body 提交提交例子
            postBody: {
                url: app_root_path + "/api/ajax/postBody",
                method: "POST",
                contentType: MediType_JSON,
                descript: "post body 提交json demo接口",
                paramModel: {
                    id: undefined,
                    text: undefined,
                    name: undefined,
                    age: undefined,
                    school: undefined,
                    teacher: {
                        name: undefined,
                        address: undefined,
                        level: undefined
                    }
                }
            },
            //普通get请求
            getRequest: {
                url: app_root_path + "/api/ajax/getRequest",
                user: {
                    id: undefined,
                    name: undefined,
                    age: undefined,
                    school: undefined,
                    teacher: {
                        teacherName: undefined,
                        cource: undefined,
                        student: {
                            teacherName: undefined,
                            cource: undefined
                        }
                    }
                }
            }
        },
        accountApi: {
            addAcount: {
                url: app_root_path + "/account/add",
            },
            updateAccount: {
                url: app_root_path + "/account/update",
            },
            deleteAccount: {
                url: app_root_path + "/account/delete",
            },
            queryAccountSimple: {
                url: app_root_path + "/account/queryAccountSimple",
            },
            permissionList: {
                url: app_root_path + "/account/permissionList",
            },
            addOrUpdateRole: {
                url: app_root_path + "/admin/role/addOrUpdate",
            },
            queryRoleKVList: {
                url: app_root_path + "/admin/role/queryKVList"
            }
        },
        dictionApi: {
            addOrUpdateDetail: {
                url: app_root_path + "/dicttionary/detail/addOrUpdate",
                model: {
                    id: undefined, //字典id,更新有值，添加无值 类型:long 必选(否)
                    dataDictionaryId: undefined, //字典类型id 类型:long 必选(是)
                    detailParentId: undefined, //父级id 类型:long 必选(否)
                    dictionaryDetailName: undefined, // 字典名称 类型:string 必选(是)
                    dictionaryDetailKey: undefined, // 键名 类型:string 必选(是)
                    dictionaryDetailValue: undefined, //键值不能为空 类型:integer 必选(是)
                    display: undefined // 类型:boolean 必选(未知)
                }
            }

        },
        roleApi: {
            addOrUpdateRoleRela: {
                url: app_root_path + "/role/relation/addOrUpdate",
                model: {
                    id: undefined, // 类型:long 必选(未知)
                    roleId: undefined, // 类型:long 必选(未知)
                    departId: undefined, // 类型:long 必选(未知)
                    positionId: undefined, // 类型:long 必选(未知)
                    uid: undefined // 类型:long 必选(未知)
                }
            },
            deleteRoleRela: {
                url: app_root_path + "/role/relation/delete",
                model: {
                    id: undefined, // 类型:long 必选(未知)
                }
            },
            queryKVList: {
                url: app_root_path + "/admin/role/queryKVList",
            },
            roleDelete: {
                url: app_root_path + "/admin/role/delete",
            },
            relatSearchList: {
                url: app_root_path + "/role/relation/searchList",
            }
        },
        departApi: {
            delete: {
                url: app_root_path + "/basedata/department/delete",
                model: {
                    id: undefined, // 类型:long 必选(未知)
                }
            }

        },
        offlineOrderApi: {
            addOrUpdate: {
                url: app_root_path + "/order/offline/add",
                model: {
                    id: undefined, //订单id,添加无值，更新有值 类型:long 必选(否)
                    orderCode: undefined, //订单编码,如果为空后台自动创建 类型:string 必选(否)
                    custId: undefined, //客户id不能为空 类型:long 必选(是)
                    signOrderId: undefined, //签单人id不能为空 类型:long 必选(是)
                    signOrderDate: undefined, //签单日期 类型:string 必选(是)
                    talkOrderId: undefined, //谈单人id不能为空 类型:long 必选(是)
                    payMethod: undefined, //支付方式(1:现金,2:支票,3:银行转帐,4:支付宝,5:微信) 类型:integer 必选(是)
                    wechatMallName: undefined, //微商城名称 类型:string 必选(否)
                    wechatMallOrder: undefined, //微商城订单号 类型:string 必选(否)
                    wechatMallPriceStr: undefined, //微商城价格 类型:string 必选(否)
                    wechatMallPrice: undefined, //微商城价格(内部转换) 类型:integer 必选(否)
                    iswechatMall: undefined, //是否使用微商城 类型:string 必选(否)
                    voucherCode: undefined, //微商城名称 类型:string 必选(否)
                    voucherPriceStr: undefined, //优惠券金额 类型:string 必选(否)
                    voucherPrice: undefined, //优惠券金额(内部转换用) 类型:integer 必选(否)
                    userid: undefined, //操作人 类型:long 必选(否)
                    isvoucher: undefined, //是否使用优惠券(0不使用，1使用) 类型:int 必选(否)
                    couponStatus: undefined, //优惠券使用状态:0:无使用，1:使用优惠券，2：使用微商城商品优惠 类型:int 必选(否)
                    strline: [ //sku服务列表 类型:list<servicebean> 必选(是)
                        {
                            did: undefined, //订单明细ID 类型:long 必选(否)
                            serviceId: undefined, //skuid服务型类 类型:long 必选(否)
                            serviceCode: undefined, //服务分类该参数与scCode一样的，对接的是前端 类型:string 必选(否)
                            specificName: undefined, //具体名称 类型:string 必选(否)
                            number: undefined, //数量 类型:integer 必选(否)
                            seriesNum: undefined, //系列数量 类型:integer 必选(否)
                            downPaymentStr: undefined, //首期费用 类型:string 必选(否)
                            downPayment: undefined, //首期费用(内部) 类型:integer 必选(否)
                            lateFees: undefined, //后期费用 类型:string 必选(否)
                            remark: undefined, //备注 类型:string 必选(否)
                            scCode: undefined, //分类编码 类型:string 必选(否)
                            skuId: undefined //分类编码 类型:string 必选(否)
                      }]
                }
            },
            update: {
                url: app_root_path + "/order/offline/update",
                model: {
                    id: undefined, //订单id,添加无值，更新有值 类型:long 必选(否)
                    orderCode: undefined, //订单编码,如果为空后台自动创建 类型:string 必选(否)
                    custId: undefined, //客户id不能为空 类型:long 必选(是)
                    signOrderId: undefined, //签单人id不能为空 类型:long 必选(是)
                    signOrderDate: undefined, //签单日期 类型:string 必选(是)
                    talkOrderId: undefined, //谈单人id不能为空 类型:long 必选(是)
                    payMethod: undefined, //支付方式(1:现金,2:支票,3:银行转帐,4:支付宝,5:微信) 类型:integer 必选(是)
                    wechatMallName: undefined, //微商城名称 类型:string 必选(否)
                    wechatMallOrder: undefined, //微商城订单号 类型:string 必选(否)
                    wechatMallPriceStr: undefined, //微商城价格 类型:string 必选(否)
                    wechatMallPrice: undefined, //微商城价格(内部转换) 类型:integer 必选(否)
                    iswechatMall: undefined, //是否使用微商城 类型:string 必选(否)
                    voucherCode: undefined, //微商城名称 类型:string 必选(否)
                    voucherPriceStr: undefined, //优惠券金额 类型:string 必选(否)
                    voucherPrice: undefined, //优惠券金额(内部转换用) 类型:integer 必选(否)
                    userid: undefined, //操作人 类型:long 必选(否)
                    isvoucher: undefined, //是否使用优惠券(0不使用，1使用) 类型:int 必选(否)
                    couponStatus: undefined, //优惠券使用状态:0:无使用，1:使用优惠券，2：使用微商城商品优惠 类型:int 必选(否)
                    strline: [ //sku服务列表 类型:list<servicebean> 必选(是)
                        {
                            did: undefined, //订单明细ID 类型:long 必选(否)
                            serviceId: undefined, //skuid服务型类 类型:long 必选(否)
                            serviceCode: undefined, //服务分类该参数与scCode一样的，对接的是前端 类型:string 必选(否)
                            specificName: undefined, //具体名称 类型:string 必选(否)
                            number: undefined, //数量 类型:integer 必选(否)
                            seriesNum: undefined, //系列数量 类型:integer 必选(否)
                            downPaymentStr: undefined, //首期费用 类型:string 必选(否)
                            downPayment: undefined, //首期费用(内部) 类型:integer 必选(否)
                            lateFees: undefined, //后期费用 类型:string 必选(否)
                            remark: undefined, //备注 类型:string 必选(否)
                            scCode: undefined, //分类编码 类型:string 必选(否)
                            skuId: undefined //分类编码 类型:string 必选(否)
                        }]
                }
            }

        },


    }
}

if (!NetUtis) {
    var NetUtis = {
        /**
         * @param api 对象
         * @param params 参数，统一json格式
         * @param callback 请求回调，据需求是否传入
         */
        request: function (api, params, callback, unPrompt, unPrintLog) {
            switch (api.method) {
                case "GET":
                    this.doGet(api, params, callback, unPrompt, unPrintLog);
                    break;
                case "POST":
                    if (api.contentType == MediType_JSON) {
                        this.doPostBody(api, params, callback, unPrompt, unPrintLog);
                    } else {
                        this.doPostForm(api, params, callback, unPrompt, unPrintLog);
                    }
                    break;
                default:
                    //默认为get
                    this.doGet(api, params, callback, unPrompt, unPrintLog);
                    break;
            }
        },
        /**
         * get方法提交数据
         * @param api 对象
         * @param params 参数，统一json格式
         * @param callback 请求回调，据需求是否传入
         */
        doGet: function (api, params, callback, unPrompt, unPrintLog) {
            api.method = "GET";
            api.contentType = MediType_JSON;
            this.doSend(api, params, callback, unPrompt, unPrintLog);
        },
        doGetSimple: function (url, params, callback, unPrompt, unPrintLog) {
            var api = {
                url: url,
                method: "GET",
                contentType: MediType_JSON
            }
            this.doSend(api, params, callback, unPrompt, unPrintLog);
        },
        /**
         * post方法 form表单提交数据，
         * @param api 对象
         * @param params 参数，统一json格式
         * @param callback 请求回调，据需求是否传入
         */
        doPostForm: function (api, params, callback, unPrompt, unPrintLog) {
            api.method = "POST";
            api.contentType = MediType_FORM_URLENCODE;
            this.doSend(api, params, callback, unPrompt, unPrintLog);
        },
        doPostFormSimple: function (url, params, callback, unPrompt, unPrintLog) {
            var api = {
                url: url,
                method: "POST",
                contentType: MediType_FORM_URLENCODE
            }
            this.doSend(api, params, callback, unPrompt, unPrintLog);
        },
        /**
         * post json格式，body 里提交数据
         * @param api 对象
         * @param params 参数，统一json格式
         * @param callback 请求回调，据需求是否传入
         */
        doPostBody: function (api, params, callback, unPrompt) {
            var tparam = JSON.stringify(params);
            api.method = "POST";
            api.contentType = MediType_JSON;
            this.doSend(api, tparam, callback, unPrompt);
        },
        doPostBodySimple: function (url, params, callback, unPrompt, unPrintLog) {
            var tparam = JSON.stringify(params);
            var api = {
                url: url,
                method: "POST",
                contentType: MediType_JSON,
            }
            this.doSend(api, tparam, callback, unPrompt, unPrintLog);
        },
        doSend: function (api, params, callback, unPrompt, unPrintLog) {
            this.doLogBefore(api, params)
            var _this = this;
            $.ajax({
                type: api.method, //请求方式
                url: api.url, //请求地址
                dataType: "json",//client接收数据类型
                data: params,
                headers: {'Content-Type': api.contentType},
                success: function (data) {
                    _this.doAfterRequest(data, callback, unPrintLog);
                    switch (data.code) {
                        case 0:
                            if (!unPrompt) {
                                layer.msg(data.msg, {icon: 7});  //成功
                            }
                            break;
                        case 1:
                            if (!unPrompt) {
                                layer.msg(data.msg, {icon: 5}); //失败
                            }
                            break;
                        case 9999: //超时
                            layer.msg(data.msg, {icon: 5});
                            wzERP.Common.TimeoutLogin();
                            break;
                        default:
                            if (!unPrompt) {
                                layer.msg(data.msg, {icon: 2});  //默认
                            }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg("请求失败", {icon: 5}); //失败
                    console.error("请求信息失败 status:" + XMLHttpRequest.status)
                }
            });
        },
        doLogBefore: function (api, reqParams) {
            if (Api.debug) {
                if (api.url == undefined) {
                    console.error("注意:没指定请求路径");
                    alert("注意:没指定请求路径,请检查代码");
                }
                if (api.descript) {
                    console.info("请求接口:" + api.url + ":" + api.descript);
                } else {
                    console.info("请求接口:" + api.url);
                }
                console.log("接口详情:" + JSON.stringify(api));
                console.log("请求参数:" + JSON.stringify(reqParams));
                if (api.method == undefined) {
                    console.warn("注意:没指定请求方式，使用默认的GET试请求");
                }
                if (api.contentType == undefined) {
                    console.warn("注意:没指定发送数据提交格式，使用默认的数据提交格式:" + MediType_FORM_URLENCODE);
                }
            }
        },
        doAfterRequest: function (data, callback, unPrintLog) {
            if (Api.debug) {
                if (!unPrintLog) {
                    console.log("服务端返回结果:" + JSON.stringify(data))
                }
            }
            if (callback) {
                callback(data);
            }
        }
    };
}


/**
 * 标签参数元信息,用于获取指定容器内指定的参数名的属性的:值; 及参数值的属性的:值
 * @param container 各参数所在的容器
 * @param tagName 该值可以为标签名、className 或id,一般为className通用
 * @param dataName 要提交的参数名(key)
 * @param valueName 要提交的参数值(value)
 * @constructor
 */
function TagInfo(container, tagName, dataName, valueName) {
    //容器名称
    this.container = container;
    //目录标签：标签名，类名或id 都可以
    this.tagName = tagName;
    //自定属性数据参数的名称
    this.dataName = dataName;
    //自定义属数据参数的值的名称
    this.valueName = valueName;
}

/**
 * 在某容器内找出所需提交的参数信息(不支持多级参数)
 * @param tagInfo 参数元信息
 * @param paramModel
 */
function scanParamsByModelName(tagInfo, paramModel) {
    //复制参数model
    var params = cloneObj(paramModel);
    var els = $(tagInfo.container).find(tagInfo.tagName);
    var hashGetParams = false;
    for (var i = 0; i < els.length; i++) {
        var dataName = $(els[i]).attr(tagInfo.dataName);
        if (dataName == undefined) {
            console.warn("注意！有一个[" + els[i].tagName + "]元素中没有定义名称为[" + tagInfo.dataName + "]属性请，请核对是否漏掉的参数名");
            continue;
        }
        var value = undefined;
        if (tagInfo.valueName == "value" && (els[i].tagName == "INPUT" || els[i].tagName == "TEXTAREA" || els[i].tagName == "SELECT" )) {
            value = $(els[i]).val();
            if (value == undefined) {
                value = $(els[i]).attr(tagInfo.valueName);
            }
        } else {
            value = $(els[i]).attr(tagInfo.valueName);
        }
        if ($(els[i]).attr('type') == 'checkbox') {
            value = els[i].checked
        }
        if (value == undefined) {
            console.warn("注意！有一个[ " + els[i].tagName + " ]元素中没有定义:" + tagInfo.valueName + "属性，请核对是参数名为[" + dataName + "]的参数是否需要赋值");
            continue;
        }
        for (key in params) {
            if (key == dataName) {
                params[key] = value;
                hashGetParams = true;
            }
        }

    }
    if (!hashGetParams) {
        console.warn("一个参数值也没获取到请检查参数名是否与接口匹配:" + JSON.stringify(paramModel));
    }
    var undfinedPs = "";
    for (key in params) {
        if (params[key] == undefined) {
            undfinedPs += key + ",";
        }
    }
    if (undfinedPs) {
        console.warn("注意model中定义的参数: " + undfinedPs + "没有值，请检查是否为必传参数");
    }
    console.log("获取到的参数:" + JSON.stringify(params));
    return params;
}

var cloneObj = function (obj) {

    var newObj = {};
    if (obj instanceof Array) {
        newObj = [];
    }
    for (var key in obj) {
        var val = obj[key];
        //newObj[key] = typeof val === 'object' ? arguments.callee(val) : val; //arguments.callee 在哪一个函数中运行，它就代表哪个函数, 一般用在匿名函数中。
        newObj[key] = typeof val === 'object' ? cloneObj(val) : val;
    }
    return newObj;
};

/**
 * 处理权限按钮
 * @param name
 * @param attr
 */
function permissonHandler(forceUpdate) {
    if(forceUpdate){
        console.log("强制刷新权限数据");
    }
    var permissionListStr = localStorage.getItem('permissionList')
    if (permissionListStr) {
        try {
            var permissionList = JSON.parse(permissionListStr);
            refresshPermissUi(permissionList);
            if (permissionList.length == 0 || forceUpdate) {
                reloadPermisson();
            } else {
                console.log("不加载权限，直接渲染");
                refresshPermissUi(permissionList);
            }
        } catch (ex) {
            localStorage.clear();
        }
    } else {
        reloadPermisson();
    }
}

function reloadPermisson() {
    console.log("重新加载权限");
  NetUtis.doGetSimple("/account/permissionList", {}, function (data) {
        if (data.code == 0) {
            var permissionList = data.data;
            var permissionListStr = JSON.stringify(permissionList)
            localStorage.setItem('permissionList', permissionListStr)
            refresshPermissUi(permissionList);
        }
    }, true, false);
}

function refresshPermissUi(permissionList) {
    var els = $("[permissionUrl]");
    for (var i = 0; i < els.length; i++) {
        var url = $(els[i]).attr("permissionUrl")
        var menuText = els[i].outerText;
        if (!checkUrlExist(url,permissionList)) {
//           $(els[i]).hide();
        }
    }
}
function checkUrlExist(url, pList) {
    if (pList) {
        return doCheckExist(url, pList);
    }
    var permissionListStr = localStorage.getItem('permissionList')
    if (permissionListStr) {
        var pList = JSON.parse(permissionListStr);
        if (pList.length != 0) {
            return doCheckExist(url, pList);
        }
    }
    return false;
}
function doCheckExist(url, pList) {
    if(Api.debug){
       console.log("当前权限列表:"+pList);
    }
    for (var j = 0; j < pList.length; j++) {
        var purl = pList[j];
        if (url === purl) {
           return true;
        }
    }
    return false;
}









